//@version = 1.8
let tool = {
		name: "Slider",
		label: "Slider",
		toolbar: 'insert,99',
		icon: 'https://avatars1.githubusercontent.com/u/5500999?v=2&s=16',
		form: `
<style>
.ckeditor__slider-modal.show { display: flex; animation: show .7s }
.ckeditor__slider-modal.hide { display: none }
@keyframes show {
0%   { opacity: 0 }
100% { opacity: 1 }
}
.ckeditor__slider-modal {
position: fixed;
top: 0;
left: 0;
align-items: center;
justify-content: center;
width:100%;
height:100%;
z-index: 999;
background: RGBA(255,255,255, .7);
}
.ckeditor__slider-modal__window {
position: relative;
text-align: center;
width: 30%;
min-width: 400px;
min-height: 300px;
height: auto;
padding: 1%;
padding-bottom: 0;
background: white;
box-shadow: 0px 0px 5px 5px rgb(245 113 113);
border: 1px solid white;
overflow: hidden;
resize: auto;
}
.ckeditor__slider-modal__window__title { border-bottom: 1px solid red; font-size: larger; }
/* Tabs */
.tab-wrapper{ width: 100%; display: flex; flex-wrap: wrap; align-items: flex-start; justify-content: flex-start; font-family: sans-serif; overflow-y: auto; }
.tab-wrapper .tab-item, .tab-wrapper > input{ display: none; }
.tab-wrapper .tab-item{ background-color: #fff; width: calc(100% - 40px); max-width: 100%; padding: 20px; order: 1; }
.tab-wrapper label{
position: relative;
background-color: #e6e6e6;
height: 35px;
line-height: 35px;
min-width: 50px;
padding: 0px 20px;
text-align: center;
float: left;
color: #878685;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
align-items: center;
justify-content: center;
flex-grow: 1;
border-right: 1px solid #c7c7c7;
}
.tab-wrapper input:checked + label{ background-color: #fff; }
.tab-wrapper input:checked + label + .tab-item{display: block;}
.tab-wrapper .tab-item textarea { width: 100%; min-height: 100px; border: 1px solid #e6e6e6; }
.tab-wrapper .tab-item textarea:focus { outline: none; box-shadow: 0 0 5px 3px #e6e6e6; }
#tab-options-slider .cont{ display: flex; flex-wrap: wrap; place-content: space-between; }
#tab-options-slider .hidden { display: none }
#tab-options-slider fieldset { display: flex; border: 1px solid #e6e6e6; width: fit-content; height: fit-content; padding: 1em; place-items: center; margin-bottom: .5em; }
#tab-options-slider .abs { position: absolute; left: 0; top: 0; }
#tab-options-slider label > span { width: 100%; height: 100%; display: inline-block; }
#tab-options-slider input:checked + span { background: white; }
#tab-options-slider .tab-options-slider__margin { flex-direction: column }
#tab-options-slider input.int { width: 50px; margin: 5px; text-align: center; line-height: 25px; font-size: 12pt; }
#tab-options-slider * { user-select: none }
.ckeditor__slider-modal.transperency, .ckeditor__slider .transperency { opacity: .5 }
.ckeditor__slider-modal__window__status-bar { border-top: 1px solid #e6e6e6; padding: .5em; color: #908f8e; }
.ckeditor__slider-modal__layer__alert { display: none; padding: 2%; }
.ckeditor__slider-modal__layer__alert.show { display: flex; position: absolute; left: 0; top: 0; width: 100%; height: 100%; background: #d35050; z-index: 1; color: white; flex-direction: column; font-size: large; }
.ckeditor__slider-modal__layer__alert.show + .tab-wrapper { display: none }
</style>
<div class='ckeditor__slider-modal hide'>
<div class='ckeditor__slider-modal__window'>
<h1 class='ckeditor__slider-modal__window__title'>Добавление слайдера</h1>
<div class='ckeditor__slider-modal__layer__alert'></div>
<div class="tab-wrapper">
<input type="radio" name="tab" id="ckeditor__slider-modal__window__tab1" checked />
<label class="tab-label" for="ckeditor__slider-modal__window__tab1" nth="1">Слайдер</label>
<div class="tab-item" id="tab-options-slider">
<div class='cont'>
<fieldset class='tab-options-slider__float'>
<legend>Обтекание в тексте</legend>
<label for='tab-options-slider__float-left'>
<input id='tab-options-slider__float-left' class='hidden' type='radio' name="slider-float" value='left'>
<span class='abs'>Слева</span>
</label>
<label for='tab-options-slider__float-none'>
<input id='tab-options-slider__float-none' class='hidden' type='radio' name="slider-float" value='none' checked>
<span class='abs'>Без</span>
</label>
<label for='tab-options-slider__float-right'>
<input id='tab-options-slider__float-right' class='hidden' type='radio' name="slider-float" value='right'>
<span class='abs'>Справа</span>
</label>
</fieldset>
<fieldset class='tab-options-slider__width'>
<legend>Ширина слайдера</legend>
<input id='tab-options-slider__width' class='int' type='number' name="slider-width" placeholder='auto'  min='0' max='100' >
<span>% от контейнера</span>
</fieldset>
<fieldset class='tab-options-slider__margin'>
<legend>Отступы(px)</legend>
<input id='tab-options-slider__margin-top' class='int' type='number' name="slider-margin" min='0' max='1000' value='0'>
<div style='display:flex;'>
<input id='tab-options-slider__margin-left' class='int' type='number' name="slider-margin" min='0' max='1000' value='0'>
<input id='tab-options-slider__margin-right' class='int' type='number' name="slider-margin" min='0' max='1000' value='0'>
</div>
<input id='tab-options-slider__margin-bottom' class='int' type='number' name="slider-margin" min='0' max='1000' value='0'>
</fieldset>
<fieldset class='tab-options-slider__slides'>
<legend>Изображения</legend>
<div></div>
</fieldset>
</div></div>
<input type="radio" name="tab" id="ckeditor__slider-modal__window__tab2" />
<label class="tab-label" for="ckeditor__slider-modal__window__tab2" nth="2">Шаблон</label>
<div class="tab-item" id="tab-template-slider">
<textarea class='tab-template-slider__text'></textarea>
</div>
</div>
<div class='ckeditor__slider-modal__window__status-bar'></div>
</div>
</div>
`, //позже стоит сделать свою систему модальных окон и внедрить свой апи для тулов.
		env: {
			modal: {
				layer: '.ckeditor__slider-modal',
				window: '.ckeditor__slider-modal__window',
				tab1: '#ckeditor__slider-modal__window__tab1',
				tab2: '#ckeditor__slider-modal__window__tab2',
				controls: {
					cont: '#tab-options-slider',
					float: {
						check: 'input[name="slider-float"]:checked',
						none: '#tab-options-slider__float-none',
						left: '#tab-options-slider__float-left',
						right: '#tab-options-slider__float-right'
					},
					margin: {
						left: '#tab-options-slider__margin-left',
						top: '#tab-options-slider__margin-top',
						right: '#tab-options-slider__margin-right',
						bottom: '#tab-options-slider__margin-bottom'
					},
					width: '#tab-options-slider__width',
					slides: {
						get: ['*[id^="iCode"] [value^="$IMAGE"]', '.image-content-code:nth-of-type(1)'],
						cont: '.tab-options-slider__slides>div',
						list: [],
						template: "\
<label for='tab-options-slider__slides${num}'>\
<input id='tab-options-slider__slides${num}' class='hidden' type='checkbox' name='slider-slides' value='${val}' checked>\
<span class='abs'>${name}</span>\
</label>"
					},
					statusBar: {
						cont: '.ckeditor__slider-modal__window__status-bar',
					},
					alertLayer: {
						cont: '.ckeditor__slider-modal__layer__alert'
					},
					template: {
						cont: '.tab-template-slider__text'
					},
				}
			},
			template: '<div class="${class}" ${attr} style="${style}" > ${slides} </div>', //шаблон кода слайдера для итоговой вставки
			options: {
				float: 'none',
				cls: 'slider',
				attr: '',
				slides: '',
				style: '',
				width: '',
				margin: {
					left: 0,
					top: 0,
					right: 0,
					bottom: 0
				},
				template: ''
			},
			editorSelect: {
				tag: null
			},
			errors: {
				noSlides: {
					h: 'Ошибка',
					p: 'Нет загруженных изображений для слайдера.<br>Выберите изображения под редактором.'
				},
				nesting: {
					h: 'Ошибка',
					p: 'Слайдер не может быть вставлен в другой слайдер.'
				}
			},
			error: false,
		},
		command: function(env, editor) {
			env['modal'].visible ? env['modal'].hide() : env['modal'].show();
			//тут действия при клике на иконке инструмента
		},
		//this - текущий объект с настройками тула, env - постоянное хранилище переменных тула, editor - ссылка на экземпляр CKEDITOR,
		init: function(env, editor) {
			// 			console.log(arguments);
			// 			console.log(this);
			let eCont = editor.container;
			let getObj = mark => typeof mark == 'string' ? eCont.find(mark).$[0] : (mark.id ? eCont.find('#'+mark.id).$[0] : eCont.find([...mark.classList].map(c => '.' + c).join('')).$[0]);
			eCont.appendHtml(this.form);
			//предполагаем что классы модального окна уникальны для разных инструментов
			//готовим ссылки на контролы
			env['modal']['layer'] = getObj(env['modal']['layer']);
			env['modal']['window'] = getObj(env['modal']['window']);
			env['modal']['tab1'] = getObj(env['modal']['tab1']);
			env['modal']['tab2'] = getObj(env['modal']['tab2']);
			env['modal']['controls']['template']['cont'] = getObj(env['modal']['controls']['template']['cont']);
			env['modal']['controls']['cont'] = getObj(env['modal']['controls']['cont']);
			env['modal']['controls']['width'] = getObj(env['modal']['controls']['width']);
			env['modal']['controls']['slides']['cont'] = getObj(env['modal']['controls']['slides']['cont']);
			env['modal']['controls']['statusBar']['cont'] = getObj(env['modal']['controls']['statusBar']['cont']);
			env['modal']['controls']['alertLayer']['cont'] = getObj(env['modal']['controls']['alertLayer']['cont']);
			env['modal']['controls']['float']['none'] = getObj(env['modal']['controls']['float']['none']);
			env['modal']['controls']['float']['left'] = getObj(env['modal']['controls']['float']['left']);
			env['modal']['controls']['float']['right'] = getObj(env['modal']['controls']['float']['right']);
			env['modal']['controls']['margin']['left'] = getObj(env['modal']['controls']['margin']['left']);
			env['modal']['controls']['margin']['top'] = getObj(env['modal']['controls']['margin']['top']);
			env['modal']['controls']['margin']['right'] = getObj(env['modal']['controls']['margin']['right']);
			env['modal']['controls']['margin']['bottom'] = getObj(env['modal']['controls']['margin']['bottom']);
			editor.document.appendStyleText('.slider{border:1px dashed red}.slider.selected{border: 2px solid green;}') //добавляем стиль рамки для выделения блока слайдера в редакторе
			env['modal']['layer'].addEventListener('click', (e)=> e.target == env['modal']['layer'] ? env['modal'].hide() : null );
			//window.env = env;
			env['modal'].show = function(){
				env['editorSelect']['tag'] = editor.getSelection().getStartElement().$;
				env['options'].update();
				env['modal']['tab1'].checked = true;
				env['options']['float'] = 'none';
				env['modal']['layer'].classList.replace('hide', 'show');
				env['modal'].visible = true;
				env['modal']['controls']['slides'].update();
				if(env['editorSelect']['tag'].classList.contains(env['options_original']['cls']) || env['editorSelect']['tag'].closest(env['options_original']['cls'])) {
					env['modal'].parseOptFromSlider(env['editorSelect']['tag']);
					let slidesList = env['modal']['controls']['slides']['cont'].querySelectorAll('input');
					let slidesFromObj = env['options']['slidesFromObj'];
					slidesList.forEach(e=>{
						slidesFromObj.includes(e.value) ? e.checked = true : e.checked = false;
					});
					env['modal']['controls']['statusBar'].updateHtml(`Выбран слайдер <a>${env['editorSelect']['tag'].tagName}[${env['editorSelect']['tag'].className}]</a>. Настройки слайдера загружены.`);
				}
				env['modal'].update();
				env['modal']['controls']['template'].update();
				if(!env['options']['slides']) { env['modal']['controls']['alertLayer'].sh(env['errors']['noSlides']); return; }
			};
			env['modal'].hide = function(){
				env['modal']['layer'].classList.replace('show', 'hide');
				env['modal']['controls']['statusBar'].clear();
				env['modal'].visible = false;
				if(env['editorSelect']['tag'].classList.contains(env['options_original']['cls']) || env['editorSelect']['tag'].closest(env['options_original']['cls'])){
					env['options'].update(true);
					env['modal']['controls']['template'].update();
					env['modal']['controls']['template'].insert(true);
				} else {
					if(!env['error'] && env['options']['slides']){
						env['modal']['controls']['template'].insert();
					}
				}
				env['modal']['controls']['alertLayer'].sh();
				env['modal'].optClear();
			}
			env['modal'].optClear = ()=>{
				env['options'] = JSON.parse(JSON.stringify(env['options_original']));
				env['options'].update = env['options_original'].update;
				env['editorSelect']['tag'] = null;
			}
			env['modal'].getSlides = function(){
				let slides = env['modal']['controls']['slides']['get'].map(getter=>Array.from(document.querySelectorAll(getter))).flat();
				return slides.length ? Array.from(slides).map(e=>e.value).join(' ') : '';
			}
			env['modal'].update = ()=> {
				env['modal']['controls']['cont'].querySelectorAll('input[name="slider-float"]').forEach(fc=> fc.checked = false);
				env['modal']['controls']['float'][env['options']['float']].click();
				env['modal']['controls']['width'].value = env['options']['width'];
				env['modal']['controls']['margin']['left'].value = env['options']['margin']['left'];
				env['modal']['controls']['margin']['top'].value = env['options']['margin']['top'];
				env['modal']['controls']['margin']['right'].value = env['options']['margin']['right'];
				env['modal']['controls']['margin']['bottom'].value = env['options']['margin']['bottom'];
			}
			env['options'].update = function(update=false){
				env['options']['float'] = env['modal']['controls']['cont'].querySelector(env['modal']['controls']['float']['check']).value;
				env['options']['width'] = env['modal']['controls']['width'].value;
				env['options']['margin']['left'] = env['modal']['controls']['margin']['left'].value;
				env['options']['margin']['top'] = env['modal']['controls']['margin']['top'].value;
				env['options']['margin']['right'] = env['modal']['controls']['margin']['right'].value;
				env['options']['margin']['bottom'] = env['modal']['controls']['margin']['bottom'].value;
				if(update){
					let list = env['modal']['controls']['slides']['cont'].querySelectorAll('input:checked');
					env['options']['slides'] = Array.from(list).map(e=>e.value).join(' ');
				} else {
					env['options']['slides'] = env['modal'].getSlides();
				}
			}
			env['modal'].parseOptFromSlider = slider => {
				let cStyle = getComputedStyle(slider);
				env['options']['float'] = cStyle.float;
				env['options']['margin']['left'] = parseFloat(cStyle.marginLeft);
				env['options']['margin']['top'] = parseFloat(cStyle.marginTop);
				env['options']['margin']['right'] = parseFloat(cStyle.marginRight);
				env['options']['margin']['bottom'] = parseFloat(cStyle.marginBottom);
				env['options']['slidesFromObj'] = slider.innerText.replaceAll(' ', '').match(/(\$IMAGE\d+\$)/g);
				if(slider.style.width && slider.style.width.includes('%')) env['options']['width'] = parseFloat(slider.style.width);
			}
			env['modal']['controls']['template'].update = function(){
				let cls = env['options']['cls'];
				let attr = env['options']['attr'];
				let width = env['options']['width'];
				let float = env['options']['float'];
				let style = env['options']['style'];
				let margin = env['options']['margin'];
				let slides = env['options']['slides'];
				margin = Object.values(margin).reduce((p,n)=>p+n) != 0 ? `margin: ${margin.top}px ${margin.right}px ${margin.bottom}px ${margin.left}px; ` : 'margin:auto;';
				width = width > 0 ? `width: ${width}%; ` : '';
				float = float != 'none' ? `float: ${float}; ` : '';
				style = margin + width + float + (style ? (style.trim().substr(-1) == ';' ? style : style + ';') : '');
				env['options']['template'] = env['template'].replace(/\${(.*?)}/g, opt => {
					if(opt == '${class}') return cls;
					if(opt == '${style}') return style;
					return env['options'][opt.slice(2, -1)];
				});
				env['modal']['controls']['template']['cont'].value = env['options']['template'];
			}//обновление шаблона из текущих опций env['options']
			env['modal']['controls']['cont'].querySelectorAll('input').forEach( input => {
				input.addEventListener('change', e => {
					let c = env['modal']['controls'];
					if(['none','left','right'].includes(e.target.value)) {
						switch(e.target.value) {
							case 'none':
								c['margin']['left'].value = 0;
								c['margin']['top'].value = 0;
								c['margin']['right'].value = 0;
								c['margin']['bottom'].value = 0;
								c['width'].value = ''
								break;
							case 'left':
								c['margin']['left'].value = 0;
								c['margin']['top'].value = 10;
								c['margin']['right'].value = 10;
								c['margin']['bottom'].value = 10;
								c['width'].value = 40;
								break;
							case 'right':
								c['margin']['left'].value = 10;
								c['margin']['top'].value = 10;
								c['margin']['right'].value = 0;
								c['margin']['bottom'].value = 10;
								c['width'].value = 40;
						}
						// 						env['modal']['controls']['slides']['cont'].querySelectorAll('input').forEach(e=>e.checked = true);
					};
					env['options'].update();
					env['modal']['controls']['template'].update();
				});
			});
			env['modal']['controls']['template'].insert = (update=false)=>{
				if(update) {
					let targetSlider;
					// 					let cls = env['options']['cls'];
					// 					let attr = env['options']['attr'];
					let width = env['options']['width'];
					let float = env['options']['float'];
					// 					let style = env['options']['style'];
					let margin = env['options']['margin'];
					let slides = env['options']['slides'];
					if(env['editorSelect']['tag'].classList.contains(env['options_original']['cls'])) {
						targetSlider = env['editorSelect']['tag']
					} else {
						targetSlider = env['editorSelect']['tag'].closest(env['options_original']['cls']);
					}
					targetSlider.style.width = width > 0 ? width+'%' : '';
					targetSlider.style.float = float;
                  	if(Object.values(margin).reduce((p,n)=>p+n) != 0) {
					targetSlider.style.marginLeft = margin.left+'px';
					targetSlider.style.marginTop = margin.top+'px';
					targetSlider.style.marginRight = margin.right+'px';
					targetSlider.style.marginBottom = margin.bottom+'px';
                  } else { targetSlider.style.margin = 'auto'; }
                    targetSlider.innerText = slides;
				} else {
					let slider = CKEDITOR.dom.element.createFromHtml(env['options']['template']);
					editor.insertElement(slider);
				}
			}//вставка шаблона в редактор
			env['options_original'] = JSON.parse(JSON.stringify(env['options']));
			env['options_original'].update = env['options'].update;
			env['modal']['controls']['statusBar'].clear = ()=> env['modal']['controls']['statusBar']['cont'].innerText = '';
			env['modal']['controls']['statusBar'].update = msg=> env['modal']['controls']['statusBar']['cont'].innerText = msg;
			env['modal']['controls']['statusBar'].updateHtml = msg=> env['modal']['controls']['statusBar']['cont'].innerHTML = msg;
			env['modal']['controls']['alertLayer'].sh = (msg)=> {//show\hide
				let aCont = env['modal']['controls']['alertLayer']['cont'];
				aCont.innerHTML = msg ? `<h2>${msg.h}</h2><p>${msg.p}</p>` : '';
				if(!msg) { aCont.classList.remove('show'); env['error'] = false; return; }
				env['error'] = true;
				aCont.classList.add('show');
			}
			env['modal']['controls']['statusBar']['cont'].addEventListener('mouseover', (e)=>{
				if(e.target.nodeName != 'A') return;
				env['modal']['layer'].classList.add('transperency');
				env['editorSelect']['tag'].classList.add('selected');
			});
			env['modal']['controls']['statusBar']['cont'].addEventListener('mouseout', (e)=>{
				if(e.target.nodeName != 'A') return;
				env['modal']['layer'].classList.remove('transperency');
				env['editorSelect']['tag'].classList.remove('selected');
			});
			env['modal']['controls']['slides'].update = ()=> { //заполняем контрол - селектор слайдов
				let list = [];
				let cont = env['modal']['controls']['slides']['cont'];
				let templ = env['modal']['controls']['slides']['template'];
				let slides = env['options']['slides'];
				if(!slides) { console.warn('Нет выбранных изображений на странице'); return; }
				slides.split(' ').map((e,i)=> {
					list.push(templ.replace(/\${(.*?)}/g, opt => {
						if(opt == '${num}') return i;
						if(opt == '${name}' || opt == '${val}') return e;
					}));
				});
				env['modal']['controls']['slides']['cont'].innerHTML = list.join('');
				list = env['modal']['controls']['slides']['cont'].querySelectorAll('input');
				list.forEach(img => img.addEventListener('change', (e)=>{
					let s = slides.split(' ');
					if(e.target.checked) {
						if(!s.includes(e.target.value)) s.push(e.target.value);
					} else {
						if(s.includes(e.target.value)) s.splice(s.indexOf(e.target.value), 1);
					}
					slides = s.join(' ');
					env['options']['slides'] = slides;
					env['modal']['controls']['template'].update();
				}));
			}
		}
}
export {tool}